package com.lh.job.task;

import com.lh.common.entity.admin.ActivityShopOne;
import com.lh.common.entity.admin.Period;
import com.lh.common.entity.admin.UserCode;
import com.lh.common.entity.admin.WinningAnnouncement;
import com.lh.common.enums.*;
import com.lh.common.utils.MathUtil;
import com.lh.job.dao.ActivityShopOneMapper;
import com.lh.job.dao.OrderMapper;
import com.lh.job.dao.PeriodMapper;
import com.lh.job.service.PeriodService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;

/**
 * @author FH
 * @ClassName: Draw a prize
 * @Description: (开奖)
 * @date: 2020-05-21 14:48
 */
@Component("shopOneTask")
@Slf4j
@Transactional(isolation= Isolation.SERIALIZABLE,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
public class ShopOneTask implements ITask{
    @Autowired
    private PeriodService periodService;

    @Autowired
    private ActivityShopOneMapper activityShopOneMapper;

    @Autowired
    private OrderMapper orderMapper;

    private ExecutorService executorService = Executors.newFixedThreadPool(8);
    /**
     * 开奖
     * */
    @Override
    public void run(String params) {
        List<Period> periods = periodService.queryPeriodList();
        for(Period period : periods){
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Date date = new Date();
                        String lotteryTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(period.getLotteryTime());
                        String newDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                        BigDecimal sumOrderPrice = periodService.sumOrderPrice(period.getPid());
                        if(sumOrderPrice == null){
                            sumOrderPrice = BigDecimal.valueOf(0);
                        }
                        Period byId = periodService.queryPeriod(period.getAid());
                        if(period.getPid().equals(byId.getPid())&&byId.getStatus().equals(PeriodStatusEnum.PROCESSING)){
                            if ((lotteryTime.compareTo(newDate) <= 0 && period.getStatus().equals(PeriodStatusEnum.PROCESSING))) {
                                log.info("当前活动ID{}当前期数ID{}与状态{}",period.getAid(),byId.getPid(),byId.getStatus());
                                ActivityShopOne activityShopOne = activityShopOneMapper.queryActivityShop(period.getAid());
                                UserCode userCode = new UserCode();
                                if(period.getIsRobot().equals(IsRobotEnum.ROBOT)){
                                    userCode = periodService.queryRobotCodeList(period.getPortionNum(),period.getPid(),period.getAid(),activityShopOne.getShopActivityPrice());
                                    activityShopOne.setSumProfitAmount(MathUtil.add(sumOrderPrice,activityShopOne.getProfitAmount()));
                                }else {
                                    //先算出夺宝码
                                    String code = periodService.queryCode(period.getPid(), period.getPortionNum());
                                    userCode = periodService.queryUserCodeList(code,period.getPid());
                                    if(userCode == null){
                                        userCode = periodService.queryRobotCodeList(period.getPortionNum(),period.getPid(),period.getAid(),activityShopOne.getShopActivityPrice());
                                        activityShopOne.setSumProfitAmount(MathUtil.add(sumOrderPrice,activityShopOne.getProfitAmount()));
                                    }else {
                                        activityShopOne.setSumProfitAmount(BigDecimal.valueOf(0));
                                    }
                                }
                                period.setStatus(PeriodStatusEnum.REVEALED);
                                period.setCode(userCode.getPeriodCode());
                                period.setUid(userCode.getUid());
                                period.setOrderItem(userCode.getOrderItem());
                                periodService.updatePeriod(period);
                                orderMapper.updateUserWin(period.getPid(), userCode.getPeriodCode());
                                WinningAnnouncement winningAnnouncement = new WinningAnnouncement();
                                winningAnnouncement.setUid(userCode.getUid());
                                winningAnnouncement.setUname(userCode.getName());
                                winningAnnouncement.setShopId(activityShopOne.getShopId());
                                winningAnnouncement.setShopName(activityShopOne.getShopName());
                                winningAnnouncement.setShopProperty(activityShopOne.getProperty());
                                winningAnnouncement.setPeriod(period.getPeriod());
                                winningAnnouncement.setPeriodCode(userCode.getPeriodCode());
                                activityShopOneMapper.insertWinRecord(winningAnnouncement);
                                orderMapper.updateOrderLoseStatus(period.getPid(), period.getAid());
                                activityShopOne.setActivityStatus(ActivityStatusEnum.FINISH);
                                if (activityShopOne.getStatus().equals(UpperLowerShelfStatus.UPPERSHELF)) {
                                    period.setAid(activityShopOne.getAid());
                                    period.setActivityName(activityShopOne.getActivityName());
                                    period.setPeriod(period.getPeriod()+1);
                                    period.setPortionNum(activityShopOne.getPortionNum());
                                    period.setTotalPortion(activityShopOne.getPortionNum());
                                    period.setActivityCycle(activityShopOne.getActivityCycle());
                                    period.setActivityStartTime(null);
                                    period.setLotteryTime(new Date(date.getTime()+activityShopOne.getActivityCycle()*1000));
                                    periodService.insertPeriod(period);
                                    if(activityShopOne.getActivityType().equals(LotteryTypeStatus.STARTNOW)){
                                        activityShopOne.setActivityStartTime(null);
                                    }else if(activityShopOne.getActivityType().equals(LotteryTypeStatus.STARTTIME)){
                                        activityShopOne.setActivityStartTime(new Date(date.getTime()+activityShopOne.getActivityCycle()*1000+10000));
                                    }
                                    activityShopOne.setActivityStatus(ActivityStatusEnum.UNDERWAY);
                                }
                                activityShopOne.setIsRobot(activityShopOne.getSumProfitAmount().compareTo(activityShopOne.getProfitAmount()) > 0 ? IsRobotEnum.CALRULES : IsRobotEnum.ROBOT);
                                activityShopOneMapper.updateActivityShopOne(activityShopOne);
                            }
                        }
                    }catch (Exception e){
                        log.error("执行异常{}:{}", period.toString(),e);
                    }
                }
            });
        }

    }
}
